package cn.dglydrpy.study.algorithm.od;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author Yyy
 * @date 2024/11/7 16:50
 * @description
 * 给定一个均衡字符串（只包含大写的 X 和 Y 两种字符且两种字符个数相同），求可分割成新的均衡子串的最大个数
 输入：XXYYXY
 输出：2
 */
public class Od0018_SplitString {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String input = scanner.nextLine();
            
            int myAnswer = myAnswer(input);
            System.out.println(myAnswer);
            int answer1 = answer1(input);
            System.out.println(answer1);
        }
                
    }

    private static int answer1(String string) {
        // 分别统计 X Y 的个数
        int xNum = 0;
        int yNum = 0;
        char[] chars = string.toCharArray();
        // 存储子字符串的集合
        List<String> list = new ArrayList<>();
        // 分割下标
        int index = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == 'X') {
                xNum++;
            } else {
                yNum++;
            }
            // 若此 X 和 Y 出现个数相等
            if (xNum == yNum) {
                // 将均衡字符串加入集合
                list.add(string.substring(index, i + 1));
                // 将分割指针更新
                index = i + 1;
                // 将记录 XY 的数量清零
                xNum = 0;
                yNum = 0;
            }
        }
        return list.size();
    }

    private static int myAnswer(String input) {
        if(input == null || input.length() == 0){
            return 0;
        }
        
        int ans = 0;
        int xcount = 0;
        int ycount = 0;
        char[] chars = input.toCharArray();
        for(int i = 0;i<chars.length;i++){
            if(chars[i] == 'X'){
                xcount++;
            }
            if(chars[i] == 'Y'){
                ycount++;
            }
            if(xcount == ycount && xcount != 0){
                ans++;
                xcount = 0;
                ycount = 0;
            }
        }

        return ans;
    }
    
}
